package com.yingxin.yx.framework.security.handler;


import com.yingxin.yx.framework.security.exception.NotRefreshTokenException;
import com.yingxin.yx.framework.security.exception.RefreshTokenException;
import com.yingxin.yx.framework.web.ResultUtil;
import com.yingxin.yx.framework.web.resp.RespHttp;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户未登录处理类
 */
@Component
public class UserAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    /**
     * 用户未登录返回结果
     * 它在用户请求处理过程中遇到认证异常时
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        // ResultUtil.responseJson(response,ResultUtil.resultCode(401,"未登录"));
        RespHttp resp = new RespHttp();
        if (exception instanceof NotRefreshTokenException) {
            resp.setSuccess(true);
            resp.setCode("0");
            resp.setTokenExpire("1");
            resp.setMsg("请重新登录");
        } else if (exception instanceof RefreshTokenException) {
            resp.setSuccess(true);
            resp.setCode("RT");
            resp.setTokenExpire("1");
            resp.setMsg("请重新登录");
        } else {
            resp.setSuccess(false);
            resp.setCode("401");
            resp.setTokenExpire("1");
            resp.setMsg("未登录");
        }
        ResultUtil.responseJson(request, response, resp);
    }
}